package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获得日期集合
        List<LocalDate> dateList = getLocalDates(begin, end);
        //营业额集合
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据（营业额是指：状态为"已完成"的订单金额合计）
            LocalDateTime beginTime = getLocalDateTimeMin(date);
            LocalDateTime endTime = getLocalDateTimeMax(date);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //如果为null，则设置0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //封装TurnoverReportVO返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获得日期集合
        List<LocalDate> dateList = getLocalDates(begin, end);
        //新增用户数量集合
        List<Integer> newUserList = new ArrayList<>();
        //总用户数量
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的用户数量
            LocalDateTime beginTime = getLocalDateTimeMin(date);
            LocalDateTime endTime = getLocalDateTimeMax(date);
           /*
           Integer newUserNumber =  userMapper.countByTime(beginTime, endTime);
           newUserList.add(newUserNumber);
           Integer totalUserNumber = userMapper.countByTime(null,endTime);
           totalUserList.add(totalUserNumber);
           */
            Map map = new HashMap();
            //查询总用户数量
            map.put("end", endTime);
            Integer totalUserNumber = userMapper.countByTime(map);
            totalUserList.add(totalUserNumber);
            //查询新增用户数量
            map.put("begin", beginTime);
            Integer newUserNumber = userMapper.countByTime(map);
            newUserList.add(newUserNumber);
        }
        //封装UserReportVO返回结果
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //获得日期集合
        List<LocalDate> dateList = getLocalDates(begin, end);
        //每日订单总数集合
        List<Integer> orderCountList = new ArrayList<>();//每日订单总数集合
        //每日有效订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = getLocalDateTimeMin(date);
            LocalDateTime endTime = getLocalDateTimeMax(date);
            //查询每天的订单总数
            Integer totalOrderCount = getOrderCount(beginTime, endTime, null);
            orderCountList.add(totalOrderCount);
            //查询每天的有效订单总数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(validOrderCount);
        }
        LocalDateTime beginTime = getLocalDateTimeMin(begin);
        LocalDateTime endTime = getLocalDateTimeMax(end);

        /*
        //查询总订单数（查询也是可以的）
        Integer totalOrderCount = getOrderCount( beginTime, endTime, null);
        //查询有效订单数
        Integer validOrderCount =  getOrderCount( beginTime, endTime, Orders.COMPLETED);
        */

        //查询总订单数(每天的订单总数加起来就等于这段时间的总订单数)
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //查询有效订单数(每天的有效订单总数加起来就等于这段时间的有效订单总数)
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime localDateTimeMin = getLocalDateTimeMin(begin);
        LocalDateTime localDateTimeMax = getLocalDateTimeMax(end);
        //查询销量排名top10
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(localDateTimeMin, localDateTimeMax);
        //获得商品名称集合和销量集合
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //封装SalesTop10ReportVO返回结果
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1、查询数据库获取营业数据--查询最近三十天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime localDateTimeMin = getLocalDateTimeMin(dateBegin);
        LocalDateTime localDateTimeMax = getLocalDateTimeMax(dateEnd);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(localDateTimeMin, localDateTimeMax);
        //2、通过POI 将数据写入到Excel文件中
        try (
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
                //创建缓冲输入流
                BufferedInputStream bis = new BufferedInputStream(in);
                //基于Excel模板文件创建新的Excel文件
                XSSFWorkbook excel = new XSSFWorkbook(bis);

                //获得输出流
                ServletOutputStream out = response.getOutputStream();
                //创建缓冲输出流
            BufferedOutputStream bos = new BufferedOutputStream(out);
        ) {
            //获得名字为Sheet1的标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间（第二行第二个）
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            //填充数据--营业额（第四行第三个）
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充数据--订单完成率（第四行第五个）
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充数据--新增用户数（第四行第七个）
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第五行
            row = sheet.getRow(4);
            //填充数据--有效订单数（第五行第三个）
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充数据--平均客单价（第五行第五个）
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充数据--明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                LocalDateTime dateMin = getLocalDateTimeMin(date);
                LocalDateTime dateMax = getLocalDateTimeMax(date);
                BusinessDataVO businessData = workspaceService.getBusinessData(dateMin,dateMax);
                //获得第7-36行
                row = sheet.getRow(7 + i);
                //填充日期 日期 营业额 有效订单 订单完成率 平均客单价 新增用户数
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //3、通过输出流将Excel文件下载到客户端浏览器下载（输出流见上面try括号里面的）
              excel.write(bos);
              bos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


//    -----------------------------------------------方法区域---------------------------------------------------------------------------------

    /**
     * 获得指定日期的23:59:59
     *
     * @param date
     * @return
     */
    private static LocalDateTime getLocalDateTimeMax(LocalDate date) {
        LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
        return endTime;
    }

    /**
     * 获得指定日期的00:00:00
     *
     * @param begin
     * @return
     */
    private static LocalDateTime getLocalDateTimeMin(LocalDate begin) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        return beginTime;
    }

    /**
     * 查询指定日期对应的订单数量
     *
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByStatus(map);
    }

    /**
     * 获得从begin到end的所有日期，包括begin和end
     *
     * @param begin
     * @param end
     * @return
     */
    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end之间的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            //日期计算，日期加一
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }


}
